package com.feicheng.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.Client;
import com.feicheng.persistence.service.IClientService;
import com.feicheng.service.impl.FPayServiceImpl;
import com.feicheng.wxapi.pay.WxAppPayBean;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/")
public class PayController {

    @Autowired
    WxAppPayBean wxAppPayBean;

    @Autowired
    HttpSession session;

    @Autowired
    IClientService iClientService;

    @Autowired
    FPayServiceImpl payService;

//    @Transactional
//    @PostMapping("/wx/pay/product/test")
//    public ResultInfo payProductTest(@RequestBody JSONObject param) {
//
//        Client client = param.getObject("client", Client.class);
//        AProduct product = param.getObject("product", AProduct.class);
//
//        AOrder order = new AOrder();
//        order.setOrderid(StringGenerator.getID("ODP"));
//        order.setAmount(product.getPrice());
//        order.setClientid(client.getClientid());
//
//
//        JSONObject info = new JSONObject();
//        info.put("product", product);
//        order.setInfo(info.toJSONString());
//        orderService.save(order);
//
//        payService.orderPaySuccess(order);
//
//        return ResultInfo.success();
//    }
//
//
//    @Transactional
//    @PostMapping("/wx/pay/type/test")
//    public ResultInfo payTypeest(@RequestBody JSONObject param) {
//
//        Client client = param.getObject("client", Client.class);
//        ATestType type = param.getObject("type", ATestType.class);
//
//        AOrder order = new AOrder();
//        order.setOrderid(StringGenerator.getID("ODT"));
//        order.setAmount(type.getPrice());
//        order.setClientid(client.getClientid());
//
//
//        JSONObject info = new JSONObject();
//        info.put("type", type);
//        order.setInfo(info.toJSONString());
//        orderService.save(order);
//
//        payService.orderPaySuccess(order);
//
//        return ResultInfo.success();
//    }


    @Transactional
    @PostMapping("/wx/pay/product")
    public ResultInfo payProduct(@RequestBody JSONObject param) {

        Client client = param.getObject("client", Client.class);

        /**
         * @param outTradeNo  本地订单编号 （payment_record -> pay_id
         * @param description 描述
         * @param notifyUrl   回调地址
         * @param amount      金额
         * @param openId      客户的openId
         */
        PrepayWithRequestPaymentResponse prepayData =
                wxAppPayBean.jsapi(
                        "订单ID",
                        "支付订单",
                        "/notice-url/"+"订单ID",
                        0,
                        client.getOpenid()
                );
        String prepayId = prepayData.getPackageVal().split("=")[1];
        JSONObject info = new JSONObject();

        return ResultInfo.success(prepayData);
    }

    @Transactional
    @PostMapping("/wx/pay/type")
    public ResultInfo payType(@RequestBody JSONObject param) {

        Client client = param.getObject("client", Client.class);


        /**
         * @param outTradeNo  本地订单编号 （payment_record -> pay_id
         * @param description 描述
         * @param notifyUrl   回调地址
         * @param amount      金额
         * @param openId      客户的openId
         */
        PrepayWithRequestPaymentResponse prepayData =
                wxAppPayBean.jsapi(
                        ""+"订单ID",
                        "支付订单",
                        "/notice-url/"+"订单ID",
                        0,
                        client.getOpenid()
                );
        String prepayId = prepayData.getPackageVal().split("=")[1];
        JSONObject info = new JSONObject();
        return ResultInfo.success(prepayData);
    }

    @Transactional
    @PostMapping("/notice-url/{orderId}")
    public JSONObject noticeOrderPay(
            @RequestHeader("Wechatpay-Nonce") String nonce,
            @RequestHeader("Wechatpay-Signature") String signature,
            @RequestHeader("Wechatpay-Signature-Type") String signatureType,
            @RequestHeader("Wechatpay-Timestamp") String timestamp,
            @RequestHeader("Wechatpay-Serial") String serial,
            @RequestBody String body,
            @PathVariable("orderId") String orderId) {

        JSONObject result = new JSONObject();
        log.info("回调成功-----------------------------------------------------------------");
        log.info(body);
        try {
            synchronized (orderId.toString().intern()) {
                Transaction transaction =
                        wxAppPayBean.parseNotice(
                                nonce,
                                signature,
                                signatureType,
                                timestamp,
                                serial,
                                body);

                if (Transaction.TradeStateEnum.SUCCESS == transaction.getTradeState()) {

                    result.put("code", "SUCCESS");
                    result.put("message", "成功");
                } else {
                    result.put("code", "ERROR");
                    result.put("message", "失败");
                }

            }
        } catch (Exception e) {
            log.error("支付出现问题", e);
            result.put("code", "ERROR");
            result.put("message", "失败");
        } finally {
            return result;
        }
    }

}
